from PyQt5.QtCore import Qt
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication,QDialog,QMessageBox,QTableWidgetItem,QAbstractItemView,QMenu,QPushButton
from app.uis.Ui_category import Ui_category
from Db import Db
class Category(QDialog, Ui_category):
    def __init__(self, parent=None):
        super(Category, self).__init__(parent)
        self.setupUi(self)
        self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.tableWidget.setContextMenuPolicy(Qt.CustomContextMenu)  ######允许右键产生子菜单
        self.tableWidget.customContextMenuRequested.connect(self.generateMenu)  ####右键菜单

        self.db = Db()

        self.tableWidget.itemChanged.connect(self.table_update)#字段改变修改
        self.showtable()

        self.pushButton_2.clicked.connect(self.closeEvent)#关闭
        self.pushButton.clicked.connect(self.table_insert)#添加

    def generateMenu(self, pos):
        row_num = -1
        for i in self.tableWidget.selectionModel().selection().indexes():
            row_num = i.row()
        
        menu = QMenu()
        item1 = menu.addAction(u"删除")
        action = menu.exec_(self.tableWidget.mapToGlobal(pos))
        if action == item1:
            reply = QMessageBox.information(self,
                                    "提示",  
                                    "是否确定删除?",  
                                    QMessageBox.Yes | QMessageBox.No)
            if reply == QMessageBox.Yes:
                self.table_delete()
        else:
            return
    def closeEvent(self, event):
        self.close()
    def showtable(self):
        self.tableWidget.itemChanged.disconnect(self.table_update)
        settings = self.db.queryReturnDict("select*from category")
        count =len(settings)
        self.tableWidget.setRowCount(count)
        for i, setting in enumerate(settings):

            item_id = QTableWidgetItem(str(setting['id']))
            item_id.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)  # 设置物件的状态为只可被选择（未设置可编辑）

            self.tableWidget.setItem(i, 0, item_id)
            self.tableWidget.setItem(i, 1, QTableWidgetItem(setting['category_code']))
            self.tableWidget.setItem(i, 2, QTableWidgetItem(setting['name']))
            self.tableWidget.setItem(i, 3, QTableWidgetItem(setting['to_code']))
        self.tableWidget.itemChanged.connect(self.table_update)
    #insert,只是简单插入一个固定数据
    def table_insert(self):
        row = self.tableWidget.rowCount()
        self.tableWidget.insertRow(row)

        self.tableWidget.setItem(row, 0, QTableWidgetItem(''))
        self.tableWidget.setItem(row, 1, QTableWidgetItem(''))
        self.tableWidget.setItem(row, 2, QTableWidgetItem(''))
        self.tableWidget.setItem(row, 3, QTableWidgetItem(''))

        #以下可以加入保存数据到数据的操作
        sql = ''' 
            INSERT INTO category ('category_code','name','to_code') VALUES (?, ?, ?)
        '''
        self.db.execute(sql,('','',''))

        self.showtable()
        self.tableWidget.verticalScrollBar().setValue(self.tableWidget.verticalScrollBar().maximum())#滚动条拖动到最底部
    #update
    def table_update(self):
        row_select = self.tableWidget.selectedItems()
        if len(row_select) == 0:
            return
        id = row_select[0].text()
        category_code = row_select[1].text()
        name = row_select[2].text()
        to_code = row_select[3].text()
        # print("code: {}".format(id))
        # 以下可以加入保存数据到数据的操作
        sql = ''' 
            update category set category_code = ?,name = ?,to_code = ? where id = ?
        '''
        self.db.execute(sql,(category_code,name,to_code,id))
        self.showtable()
    #delete
    def table_delete(self):
        row_select = self.tableWidget.selectedItems()
        if len(row_select) == 0:
            return
        id = row_select[0].text()
        row = row_select[0].row()
        self.tableWidget.removeRow(row)
        # 以下可以加入保存数据到数据的操作
        sql = ''' 
            delete from category where id = '%s'
        '''%(id)
        self.db.execute(sql)
        self.showtable()